package com.zzl.study.nacos.actuator;

import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.zzl.study.nacos.NacosServiceMultiManager;
import com.zzl.study.nacos.properties.NacosMultiDiscoveryProperties;
import com.zzl.study.nacos.properties.NacosServerConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Nacos多注册中心服务发现actuator端点
 *
 * @author: zhangzl
 * @date: 2025/7/16 20:14
 * @version: 1.0
 */
@Slf4j
@Endpoint(id = "nacos-multi-discovery")
public class NacosMultiDiscoveryEndpoint {

    /**
     * Nacos多注册中心服务管理器
     */
    private NacosServiceMultiManager nacosServiceMultiManager;

    /**
     * Nacos多注册中心属性配置
     */
    private NacosMultiDiscoveryProperties nacosMultiDiscoveryProperties;

    /**
     * 构造函数
     *
     * @param nacosServiceMultiManager      Nacos多注册中心服务管理器
     * @param nacosMultiDiscoveryProperties Nacos多注册中心属性配置
     */
    public NacosMultiDiscoveryEndpoint(NacosServiceMultiManager nacosServiceMultiManager, NacosMultiDiscoveryProperties nacosMultiDiscoveryProperties) {
        this.nacosServiceMultiManager = nacosServiceMultiManager;
        this.nacosMultiDiscoveryProperties = nacosMultiDiscoveryProperties;
    }

    /**
     * 获取所有注册中心信息
     *
     * @return 注册中心信息
     */
    @ReadOperation
    public Map<String, Object> nacosMultiDiscovery() {
        Map<String, Object> result = new HashMap<>();
        result.put("NacosMultiDiscoveryProperties", this.nacosMultiDiscoveryProperties);
        Map<String, NacosServerConfiguration> multiple = this.nacosMultiDiscoveryProperties.getMultiple();
        Map<String, List<ServiceInfo>> subscribeMap = new HashMap<>(multiple.size());
        for (String registryName : multiple.keySet()) {
            NamingService namingService = this.nacosServiceMultiManager.getNamingService(registryName);
            List<ServiceInfo> subscribe = Collections.emptyList();
            try {
                subscribe = namingService.getSubscribeServices();
                for (ServiceInfo serviceInfo : subscribe) {
                    List<Instance> instances = namingService.getAllInstances(serviceInfo.getName(), serviceInfo.getGroupName());
                    serviceInfo.setHosts(instances);
                }
            } catch (Exception e) {
                log.error("get subscribe services from nacos fail,", e);
            }
            subscribeMap.put(registryName, subscribe);
        }
        result.put("subscribe", subscribeMap);
        return result;
    }

}
